using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class DialogSystem : MonoBehaviour
{
    [SerializeField] private int index;
    
    [Header("文字速度")]
    public float textSpeed = 0.1f;
    
    [Header("文本脚本")]
    public TextAsset dialogueFile;
    
    private bool isTextComplete = false;
    private bool isTypingCancelled = false;
    public TextMeshProUGUI speakerNameText;
    public TextMeshProUGUI dialogueText;
    [SerializeField]
    public List<Dialogue> dialogueList = new List<Dialogue>();
    
    private bool isPaused = false;
    public bool IsPaused => isPaused;
    private bool isClosed = true;
    public bool IsClosed => isClosed;
    // 添加表示整个对话是否完成的标志
    private bool isEntireDialogueComplete = false;
    public bool IsEntireDialogueComplete => isEntireDialogueComplete;
    
    private static DialogSystem instance;
    public static DialogSystem Instance => instance;
    void Awake()
    {
        // Initialize singleton instance
        if(instance == null) {
            instance = this;
        }/*
        else {
            Destroy(gameObject);
            return;
        }*/
        
        ParseDialogueFile(dialogueFile);
        gameObject.SetActive(false);

        // 更安全的组件获取方式
        /*TextMeshProUGUI[] texts = GetComponentsInChildren<TextMeshProUGUI>(true);
        if (texts.Length < 2)
        {
            Debug.LogError("需要至少两个TextMeshProUGUI组件（名字和对话）");
            return;
        }

        speakerNameText = texts[0];
        dialogueText = texts[1];
        Debug.Log("dialogueStart");*/
        
        isEntireDialogueComplete = true; // 初始状态为已完成
    }

    void Update()
    {
        ContinueDialogue();
    }
    
    /// <summary>
    /// 读取
    /// </summary>
    /// <param name="file"></param>
    private void ParseDialogueFile(TextAsset file)
    {
        dialogueList.Clear();
        index = 0;

        // 处理可能的BOM头和空行
        string rawText = file.text.Trim('\uFEFF');
        string[] lines = rawText.Split(new[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);

        for (int i = 1; i < lines.Length; i++) // 跳过标题行
        {
            string line = lines[i].Trim();
            if (string.IsNullOrEmpty(line)) continue;

            string[] columns = line.Split(',');
            
            // 确保至少有4列数据
            if (columns.Length < 4)
            {
                Debug.LogWarning($"跳过格式错误的行 {i}: {line}");
                continue;
            }

            string command = columns[0].Trim();
            string name = columns[1].Trim();
            string sentence = columns[2].Trim().Trim('"'); // 移除可能的引号
            
            dialogueList.Add(new Dialogue(command, name, sentence));
        }
        Debug.Log("hanshunei"+dialogueList.Count);  
    }
    
    public void StartDialogue(string command, string name)
    {
        for (int i = 0; i < dialogueList.Count; i++)
        {
            Debug.Log($"<UNK> {i}: {command}");
            if (command == dialogueList[i].command)
            {
                if (name == dialogueList[i].name)
                {
                    index = i+1;
                    gameObject.SetActive(true); 
                    Debug.Log("触发剧情\n");
                    isEntireDialogueComplete = false; // 标记整个对话开始
                    StartCoroutine(TypeText());
                    return; 
                }
            }
        }
        Debug.Log(dialogueList.Count);
        Debug.LogWarning($"未找到匹配的对话: 命令={command}, 名称={name}");
    }

    public void ContinueDialogue()
    {
        if (isPaused) return;
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0))
        {
            if (index >= dialogueList.Count) return;
            
            // 结束对话
            if (dialogueList[index].command == "结束")
            {
                StartCoroutine(CloseDialogue());
                return;
            }
            
            // 继续对话
            if (isTextComplete && !isTypingCancelled)
            {
                StartCoroutine(TypeText());
            }
            else if (!isTextComplete)
            {
                isTypingCancelled = !isTypingCancelled;
            }
        }
    }

    public void PauseDialog(bool isPaused)
    {
            this.isPaused = isPaused;
    }
    public string GetCommand()
    {
        if (dialogueList[index].command != "")
        {
            return dialogueList[index].command + "," + dialogueList[index].name;
        }
        else
        {
            return null;
        }
    }
    
    private IEnumerator TypeText()
    {
        if (index >= dialogueList.Count) yield break;
        
        gameObject.SetActive(true);
        isTextComplete = false;
        isTypingCancelled = false;
        isClosed = false;
        speakerNameText.text = dialogueList[index].name;
        dialogueText.text = "";
        
        string fullSentence = dialogueList[index].sentence;
        
        for (int i = 0; i < fullSentence.Length; i++)
        {
            if (isTypingCancelled)
            {
                dialogueText.text = fullSentence;
                isTypingCancelled = false;
                break;
            }
            
            dialogueText.text += fullSentence[i];
            yield return new WaitForSeconds(textSpeed);
        }
        
        isTextComplete = true;
        index++;
    }
    
    private IEnumerator CloseDialogue()
    {
        yield return new WaitForSeconds(0.5f);
        gameObject.SetActive(false);
        index = 0;
        isTextComplete = false;
        isTypingCancelled = false;
        isClosed = true;
        isEntireDialogueComplete = true; // 确保关闭时标记完成
    }
    
    
}